var baseUrl = 'https://api.qikuai100.com/';
var catgeroyList = {};
// 选择的资质等级
var subcategoryData = {
    subcategoryData: [],
    subCatName: []
};

var uid = localStorage.getItem("uid");
$('.userId').val(uid);


var logoSrc = ''; // 公司logo 地址

$(function() {

    initDateOne();
    $('.addBtn').click(function() {
        addCatgery();
    });
    /**
     * 上传Logo
     */
    var uploadingLogo = false;
    $("#logoIpt").on("change", function() {
        if (uploadingLogo) {
            layer.msg("文件正在上传中，请稍候");
            return false;
        }
        var indexLogo = layer.load(1, { shade: false });
        $.ajax({
            url: baseUrl + "api/img/upload",
            type: 'POST',
            cache: false,
            data: new FormData($('#logoForm')[0]),
            processData: false,
            contentType: false,
            dataType: "json",
            beforeSend: function() {
                uploadingLogo = true;
            },
            success: function(data) {
                layer.close(indexLogo);
                console.log(data);
                if (data.ret == 0) {
                    $("#logoPic").attr("src", data.data.url);
                } else {
                    layer.msg("上传logo失败");
                }
                uploadingLogo = false;
            }
        });
    });

    /**
     * 上传公司图片 1
     */
    var uploadingCompOne = false;
    $("#comIptOne").on("change", function() {
        if (uploadingCompOne) {
            layer.msg("文件正在上传中，请稍候");
            return false;
        }
        var indexLogo = layer.load(1, { shade: false });
        $.ajax({
            url: baseUrl + "api/img/upload",
            type: 'POST',
            cache: false,
            data: new FormData($('#compFormOne')[0]),
            processData: false,
            contentType: false,
            dataType: "json",
            beforeSend: function() {
                uploadingCompOne = true;
            },
            success: function(data) {
                layer.close(indexLogo);
                console.log(data);
                if (data.ret == 0) {
                    $("#comPicOne").attr("src", data.data.url);
                } else {
                    layer.msg("上传公司图片失败");
                }
                uploadingCompOne = false;
            }
        });
    });

    /**
     * 上传公司图片 2
     */
    var uploadingCompTwo = false;
    $("#comIptTwo").on("change", function() {
        if (uploadingCompTwo) {
            layer.msg("文件正在上传中，请稍候");
            return false;
        }
        var indexLogo = layer.load(1, { shade: false });
        $.ajax({
            url: baseUrl + "api/img/upload",
            type: 'POST',
            cache: false,
            data: new FormData($('#compFormTwo')[0]),
            processData: false,
            contentType: false,
            dataType: "json",
            beforeSend: function() {
                uploadingCompTwo = true;
            },
            success: function(data) {
                layer.close(indexLogo);
                if (data.ret == 0) {
                    $("#comPicTwo").attr("src", data.data.url);
                } else {
                    layer.msg("上传公司图片失败");
                }
                uploadingCompTwo = false;
            }
        });
    });

    /**
     * 上传公司图片 3
     */
    var uploadingCompThree = false;
    $("#comIptThree").on("change", function() {
        if (uploadingCompThree) {
            layer.msg("文件正在上传中，请稍候");
            return false;
        }
        var indexLogo = layer.load(1, { shade: false });
        $.ajax({
            url: baseUrl + "api/img/upload",
            type: 'POST',
            cache: false,
            data: new FormData($('#compFormThree')[0]),
            processData: false,
            contentType: false,
            dataType: "json",
            beforeSend: function() {
                uploadingCompThree = true;
            },
            success: function(data) {
                layer.close(indexLogo);
                if (data.ret == 0) {
                    $("#comPicThree").attr("src", data.data.url);
                } else {
                    layer.msg("上传公司图片失败");
                }
                uploadingCompThree = false;
            }
        });
    });

});


var catGeryChoosed = template('catGeryChoosedScript', subcategoryData);
document.getElementById('catGeryChoosed').innerHTML = catGeryChoosed;

/**
 *添加已选中的资质 *
 */
function addCatgery() {
    var idOne = $('#chooseOneSelect').children('option:selected').val(),
        idTwo = $('#chooseTwoSelect').children('option:selected').val(), // 2级资质id
        nameOne = '',
        nameTwo = '',
        str = '';
    if (idOne == '') {
        layer.msg("请选择资质类别");
        return false;
    }
    if (idTwo == '') {
        layer.msg("请选择资质专业");
        return false;
    }

    for (var i = 0; i < catgeroyList.data.length; i++) {
        if (idOne == catgeroyList.data[i].id) {
            nameOne = catgeroyList.data[i].category_name;
            for (var j = 0; j < catgeroyList.data[i].subcategoy.length; j++) {
                if (idTwo == catgeroyList.data[i].subcategoy[j].id) {
                    nameTwo = catgeroyList.data[i].subcategoy[j].category_name;
                }
            }
        }
    }
    str = nameOne + '-' + nameTwo;
    // 插入选择的资质
    if (subcategoryData.subcategoryData.length == 0) {
        subcategoryData.subcategoryData.push(idTwo);
        var jsonCreat = {
            name: str,
            id: idTwo
        };
        subcategoryData.subCatName.push(jsonCreat);
    } else {
        for (var g = 0; g < subcategoryData.subcategoryData.length; g++) {
            if (subcategoryData.subcategoryData[g] == idTwo) {
                layer.msg("请勿重复添加相同的资质");
                return false;
            }
        }
        subcategoryData.subcategoryData.push(idTwo);
        var jsonCreat = {
            name: str,
            id: idTwo
        };
        subcategoryData.subCatName.push(jsonCreat);
    }
    var catGeryChoosed = template('catGeryChoosedScript', subcategoryData);
    document.getElementById('catGeryChoosed').innerHTML = catGeryChoosed;
    console.log(subcategoryData);
}

/**
 *删除已选中的资质 *
 */
function reduceChoosed(dId) {
    for (var i = 0; i < subcategoryData.subcategoryData.length; i++) {
        if (subcategoryData.subcategoryData[i] == dId) {
            var arr = subcategoryData.subcategoryData;
            arr.splice($.inArray(dId, arr), 1)
            i--;
        }
    }
    for (var j = 0; j < subcategoryData.subCatName.length; j++) {
        if (subcategoryData.subCatName[j].id == dId) {
            var arrN = subcategoryData.subCatName;
            arrN.splice($.inArray(subcategoryData.subCatName[j], arrN), 1);
            j--;
        }
    }
    var catGeryChoosed = template('catGeryChoosedScript', subcategoryData);
    document.getElementById('catGeryChoosed').innerHTML = catGeryChoosed;
}
// 资质分类
function initDateOne() {
    $.ajax({
        type: "POST",
        url: baseUrl + "api/category/list",
        data: {
            "type": 1
        },
        success: function(result) {
            if (result.ret == 0) {
                catgeroyList = result;
                console.log(catgeroyList);
                var chooseOne = template('chooseOneScript', catgeroyList);
                document.getElementById('chooseOne').innerHTML = chooseOne;
            }
        }
    });
}

// 选择资质专业
var twoCatList = {
    name: "资质专业",
    subcategoy: []
};
$('#chooseOne').on("change", "#chooseOneSelect", function() {
    var ss = $(this).children('option:selected').val();
    if (ss) {
        for (var i = 0; i < catgeroyList.data.length; i++) {
            if (ss == catgeroyList.data[i].id) {
                twoCatList.subcategoy = catgeroyList.data[i].subcategoy;
            }
        }
    }
    var chooseTwo = template('chooseTwoScript', twoCatList);
    document.getElementById('chooseTwo').innerHTML = chooseTwo;
});
// 初始化资质专业
var chooseTwo = template('chooseTwoScript', twoCatList);
document.getElementById('chooseTwo').innerHTML = chooseTwo;

/**
 * 公司图片
 */
var arrPicList = [];

function checkCompPic() {
    var basePicUrl = 'https://img.qikuai100.com/bg.png';
    $('#compPicContainer').find("img").each(function(i, item) {
        if ($(this).attr("src") != basePicUrl) {
            arrPicList.push($(this).attr("src"));
        }
    });
}

/**
 * 提交数据
 */
function saveCompany() {
    var desc = $('#desc').val();
    var advantage = $('#advantage').val();
    var contact_name = $('#contact_name').val();
    var contact_number = $('#contact_number').val();
    var myreg = /^1[34578]\d{9}$/;
    checkCompPic();
    console.log(arrPicList);
    var basePicUrl = 'https://img.qikuai100.com/bg.png';

    if ($.trim(desc) == '') {
        layer.msg("请输入公司介绍");
        return;
    }
    if ($.trim(advantage) == '') {
        layer.msg("请输入公司优势");
        return;
    }

    if (subcategoryData.subcategoryData.length == 0) {
        layer.msg("请选择公司代办资质");
        return;
    }
    if ($("#logoPic").attr("src") == basePicUrl) {
        layer.msg("请上传公司logo");
        return;
    }
    if (arrPicList.length == 0) {
        layer.msg("请上传公司图片");
        return;
    }
    if ($.trim(contact_name) == '') {
        layer.msg("请输入对接人信息");
        return;
    }
    if ($.trim(contact_number) == '') {
        layer.msg("请输入对接人电话号码");
        return;
    }
    if (!myreg.test(contact_number)) {
        layer.msg("请输入有效的手机号码");
        return;
    }
    var subcategory_ids = {
        subcategory_ids: subcategoryData.subcategoryData
    };
    console.log(subcategory_ids);
    var album = {
        album: arrPicList
    };

    $.ajax({
        type: "POST",
        url: baseUrl + "api/company/upload",
        data: {
            "uid": uid,
            "desc": desc,
            "advantage": advantage,
            "subcategory_ids": subcategory_ids,
            "logo": $("#logoPic").attr("src"),
            "album": album,
            "contact_name": contact_name,
            "contact_number": contact_number
        },
        success: function(result) {
            console.log(result);
            if (result.ret == 0) {
                layer.msg("信息保存成功，请耐心等待审核！");
            } else {
                layer.msg(result.res_info);
            }
        }
    });
}